import apiUrls from '@/api';
import $request from "@/common/request.js";
import config from "@/common/config";
import { setStorage, getStorage } from './storage';
import dayjs from 'dayjs';
import dictMaps from './dict'; 

// 拼接静态资源url
export const stitchingURL = (name, type = 'png') => {
	if (!type || !name) {
		return false
	}
	return config.RESOURCESURL + name + '.' + type
}
// 
export const isWindows = e => {
  return e.platform === 'windows';
}
// 获取px和rpx的比列
export const pxTurnRpx = () => {
	return 750 / uni.getSystemInfoSync().windowWidth;
}
// 获取微信Code
export const getWeiXinCode = (callback) => {
  wx.login({
		success: (codeRes) => {
			if (codeRes.code) {
				if (callback) {
					callback(codeRes.code)
				}
			}
		}
	});
}
// 获取当前时间戳
export const getTimestamp = () => {
	let timestamp = Date.parse(new Date()) / 1000;
	return timestamp;
}
// 获取用户信息
export const getUserInfo = async (isHttps = true) => {
  const localUserInfo = await uni.getStorageSync("userInfo");
  const userInfo = localUserInfo ? JSON.parse(localUserInfo) : null;
	if ((!isHttps || userInfo) && userInfo?.timestamp >= getTimestamp()) {
		return userInfo;
	}
  const res = await $request.get(apiUrls.customerInfo, {
    isLoading: true
  });
  const userInfoData = {
    ...res
  }
	setStorage('userInfo', res);
  return userInfoData
}
// 获取token
export const getAccessToken = async (data) => {
	const response = await $request.post(apiUrls.loginIdentity, {
			isLoading: true,
			data: {		
				...data,
			},
		});
    return response;
}

// 微信登入
export const wxLogin = async ( code, openIdData = {}) => {
	const data = {
		code,
		// encryptedData: mobileData.encryptedData,
		// iv: mobileData.iv,
		// wxCode: code
		...openIdData
	};
	const res = await getAccessToken(data);
  return res;
}
// 防重复点击
export const preventActive = (self) => {
	self.pageActive = true;
	//设置该时间内重复触发只执行第一次，单位ms，按实际设置
	setTimeout(() => {
		self.pageActive = false;
	}, 2000);
}
// 弹窗 
export const showToast = (title = "", duration = 2000, icon = "none") => {
	uni.showToast({
		title: title,
		duration: duration,
		icon: icon,
	});
}
// 校验对象是否为空对象
export const isEmptyObj = (obj) => {
	if (!obj || !Object.keys(obj).length) {
		return true;
	}
	if (Array.isArray(obj)) {
		return !obj.length;
	}
	return !Object.keys(obj).length;
}

// 是否登入
export const isLogin = () => {
	const token = getStorage('token');
	return !!token;
}
// 用户是否认证
export const userIsVerify = () => {
	const userInfo = getStorage("userInfo");
	return String(userInfo.checkStatus) === '1';
}
//获取两日期之间日期
export const getdiffdate = (stime, etime) => {
	//初始化日期列表，数组
	let diffdate = new Array();
	let i = 0;
	//开始日期小于等于结束日期,并循环
	while (stime <= etime) {
		diffdate[i] = stime;
		//获取开始日期时间戳
		let stime_ts = new Date(stime).getTime();
		//增加一天时间戳后的日期
		let next_date = stime_ts + 24 * 60 * 60 * 1000;
		//拼接年月日，这里的月份会返回（0-11），所以要+1
		let next_dates_y = new Date(next_date).getFullYear() + "-";
		let next_dates_m =
			new Date(next_date).getMonth() + 1 < 10 ?
				"0" + (new Date(next_date).getMonth() + 1) + "-" :
				new Date(next_date).getMonth() + 1 + "-";
		let next_dates_d =
			new Date(next_date).getDate() < 10 ?
				"0" + new Date(next_date).getDate() :
				new Date(next_date).getDate();
		stime = next_dates_y + next_dates_m + next_dates_d;
		//增加数组key
		i++;
	}
	return diffdate;
}

// 通过年月日计算星期几
export const getWeek = (dateString) => {
	const dateArray = dateString.split("-");
	const date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
	return "日一二三四五六".charAt(date.getDay());
}

// 根据日期数组渲染出星期和日期
export const getArrWeek = (list) => {
	const newArray = [];
	const len = list.length
	for (var i = 0; i < len; i++) {
		const data = list[i].split("-");
		newArray.push({
			initData: list[i],
			data: data[1] + "-" + data[2],
			week: "周" + getWeek(list[i]),
		});
	}
	return newArray;
}

// 校验手机号
export const checkPhone = (digital) => {
	let reg_tel = /^(1[0-9]\d{9})$/;
	if (!reg_tel.test(digital)) {
		return false;
	}
	return true;
}

// 手机号脱敏
export const desensitization = (digital) => {
	if (!digital) {
		return false;
	}
	let pat = /(\d{3})\d*(\d{4})/;
	return digital.replace(pat, "$1****$2");
}

// 去掉标点符号
export const checkPunctuation = (str) => {
	const symbol = str.replace(
		/[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?/\，/\。/\；/\：/\“/\”/\》/\《/\|/\{/\}/\、/\!/\~/\`]/g,
		""
	);
	return symbol;
}

// 去掉数字
export const checkNumber = (str) => {
	const number = str.replace(/[\d]/g, "");
	return number;
}

// 检测数据
export const inputEnter = (e, Ename) => {
	let valNum = e.target.value;
	valNum = valNum.replace(/[^\d.]/g, ""); // 清除数字小数点以外的字符
	valNum = valNum.replace(/\.{2,}/g, "."); // 不能连续输入两个及以上小数点
	valNum = valNum
		.replace(".", "$#$")
		.replace(/\./g, "")
		.replace("$#$", "."); // 只保留第一个. 清除多余
	// 重量 2位小数
	if (Ename === "cargoWeight") {
		valNum = valNum.replace(
			/^(-)*(\d+)\.(\d\d).*$/,
			"$1$2.$3" // 只能输入2位数
		);
		valNum = valNum > 1000000 ? 1000000 : Number(valNum);
	}
	// 体积 3位小数
	if (Ename === "cargoVol") {
		valNum = valNum.replace(
			/^(-)*(\d+)\.(\d\d\d).*$/,
			"$1$2.$3" // 只能输入3位数
		);
		valNum = valNum > 1000000 ? 1000000 : Number(valNum);
	}
	// 件数  整数
	if (Ename === "boxNum") {
		valNum = valNum.replace(
			/^(-)*(\d+)\.().*$/,
			"$1$2.$3"
		);
		valNum = valNum > 1000000 ? 1000000 : Number(valNum);
	}
	return valNum;
};

// 去掉特殊符号和空格
export const checkRules = (data) => {
	if (!data) {
		return "";
	}
	const value = data.replace(
		new RegExp(
			"[^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n]",
			"gm"
		),
		""
	);
	return value.replace(/\s+/g, "");
}


// 检查对象是否为空
export const checkObject = (data) => {
	if (Object.keys(data).length === 0) {
		return false;
	}
	return true;
}


// 计算两个日期的天数
export const getDaysBetween = (dateString1, dateString2) => {
	const startDate = Date.parse(dateString1);
	const endDate = Date.parse(dateString2);
	const days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
	return days;
}

// 突出搜索关键字
export const wordColor = (str, key) => {
	let reg = new RegExp("(" + key + ")", "g");
	let newstr = (str || "").replace(
		reg,
		"<font style='color:#FB5E58;'>$1</font>"
	);
	return newstr;
}

// 将秒转成分和秒
export const pointsAndSeconds = (seconds) => {
	let points;
	points = Math.floor(seconds / 60);
	seconds = seconds % 60;
	points += '';
	seconds += '';
	points = (points.length == 1) ? '0' + points : points;
	seconds = (seconds.length == 1) ? '0' + seconds : seconds;
	return points + '分' + seconds + '秒'
}

function isNull(str) {
	if (str == "") return true;
	let regu = "^[ ]+$";
	let re = new RegExp(regu);
	return re.test(str);
}

// 是否图片
export const isImage = (str) => {
	if (!str) {
		return false;
	}
	if (/.(png|jpg|jpeg)$/g.test(str.split('?')[0].toLowerCase())) {
		return true;
	}
	return false;
};

// 是否为PDF
export const isPdf = (str) => {
	if (!str) {
		return false;
	}
	if (/.(pdf)$/g.test(str.split('?')[0].toLowerCase())) {
		return true;
	}
	return false;
};

// 打开文件的时候执行
export const isFileFormat = (str) => {
	let string = Array.isArray(str) ? str.toString() : str;
	if (isImage(string)) {
		return 'png'
	} else if (isPdf(string)) {
		return 'pdf'
	} else {
		return false
	}
}

// 查看图片
export const reviewImages = (urls, self) => {
	preventActive(self)
	uni.previewImage({
		current: urls[0],
		urls: urls,
	})
}

// 查看文件
export const checkTheFile = (url, self) => {
	preventActive(self)
	uni.showLoading({
		title: "正在打开",
		mask: true,
	});
	uni.downloadFile({
		url: url,
		success: function (res) {
			if (res.statusCode === 200) {
				const filename = !isFileFormat(url) && (res.header['Content-Disposition'] || res
					.tempFilePath) || url;
				if (isFileFormat(filename)) {
					if (isFileFormat(filename) === 'png') {
						const urls = [url]
						reviewImages(urls, self)
					} else {
						const filePath = res.tempFilePath;
						uni.openDocument({
							showMenu: true,
							filePath: filePath,
							fileType: 'pdf'
						});
					}
					uni.hideLoading();
				} else {
					uni.hideLoading();
					showToast("格式不支持");
				}
			} else {
				uni.hideLoading();
				showToast("文件已损坏");
			}
		},
		fail: function (res) {
			uni.hideLoading();
			showToast("无效域名");
		}
	});
}
export const downloadFile = (path) => {
	if (!path) {
		return ;
	}
	uni.showLoading({
		title: "文件下载中...",
		mask: true,
	});
	// 下载Excel文件
	wx.downloadFile({
		url: path, // Excel文件的URL
		success: function (res) {
			// 保存Excel文件到本地
			wx.saveFile({
				tempFilePath: res.tempFilePath,
				success: function (res) {
					uni.hideLoading();
					// 下载完成并保存成功后，可以提示用户并打开文件
					wx.showModal({
						title: '下载完成',
						content: 'Excel文件已下载至' + res.savedFilePath,
						showCancel: false,
						success: function (res) {
							if (res.confirm) {
								// 打开文件
								wx.openDocument({
									filePath: res.savedFilePath,
									success: function (res) {
										console.log('打开文档成功')
									}
								})
							}
						}
					})
				},
				fail: () => {
					uni.hideLoading();
				}
			})
		}
	})
}

// 防抖
export const debounceFn = (fn, delay = 500) => {
	let timer = null;
	// eslint-disable-next-line func-names
	return function () {
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(() => {
			// eslint-disable-next-line prefer-rest-params
			fn.apply(this, arguments);
			// 清空计时器
			timer = null;
		}, delay);
	};
}

// 节流
export const throttleFn = (fn, delay = 500) => {
	let canRun = true;
	// eslint-disable-next-line func-names
	return function () {
		if (canRun) {
			canRun = false;
			setTimeout(() => {
				canRun = true;
				fn.apply(this, arguments);
			}, delay);
		}
	};
}

// 从下单点进
export const entryForOrder = (entry) => {
	return entry === 'order';
}

export const wxgetLocation = (self) => {
	wx.getLocation({
		success: (res) => {
			// uni.showLoading({
			// 	title: "正在获取定位",
			// });
			self.$qqmapsdk.reverseGeocoder({
				// 获取表单传入的位置坐标,不填默认当前位置,示例为string格式
				location: {
					latitude: res.latitude,
					longitude: res.longitude,
				},
				success: function (res) {
					let location = {
						...self.location,
						isLocation: true,
						originProvince: res.result.address_component.province.split("省")[0],
						originCity: res.result.address_component.city.split("市")[0],
					};
					// 存入省市
					uni.setStorageSync("location", JSON.stringify(location));
					// 触发父组件更新地址信息
					// self.$emit("updateLocation");
					self.updateLocation();
					// uni.hideLoading();
				},
				fail: function (error) {
					// uni.hideLoading();
					// uni.navigateTo({
					// 	url: "/pages/index/origin",
					// });
				},
			});
		},
		fail: (e) => {
			// uni.hideLoading();
			// uni.navigateTo({
			// 	url: "/pages/index/origin",
			// });
		},
	});
}
// 分割string
export const splitStringText = (str, splitFlag = ',') => {
	if (!str || typeof str !== 'string') {
		return '';
	}
	return str.split(splitFlag)[0];
}
// 获取最近七天，共八天
export const getNearlySevenDays = () => {
	const dates = []
	for (let i = 0; i < 8; i++) {
		const date = dayjs().add(i, 'day')
		dates.push(date.format('YYYY-MM-DD'))
	}
	return dates;
}
// 获取label by key in dict
export const getLabelByDictKey = (key, mapsKey) => {
	if (!key || !dictMaps[mapsKey]) {
		return '';
	}
	const curr = dictMaps[mapsKey].find(v => v.value === key);
	return curr ? curr.label : '';
}

export const getArriveRate = (product) => {
	const rateMaps = {
		T: '99.8%',
		B: '98.6%',
		P: '96.5%',
		Z: '99%',
	}
	const other = "95%";
	return rateMaps[product] || other;
}
export const timeIsexpired = (time, day = 7) => {
	if (!time) {
		return true;
	}
	return dayjs(time).add(day, 'day').isAfter(new Date());
}
// 今天是否登陆过
export const todayIsLogin = () => {
	const login = isLogin();
	if (!login) {
		return false;
	}
	const lastLoginTime = getStorage("lastLoginTime");
	return lastLoginTime === dayjs(new Date()).format("YYYY-MM-DD");
}